//
//  WBOAuthViewController.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/15.
//  Copyright © 2016年 木木. All rights reserved.
//

import UIKit
import SVProgressHUD


let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory,.userDomainMask, true).last! as NSString) .appendingPathComponent("userInfo.plist")


class WBOAuthViewController: UIViewController {
    
       let  webView = UIWebView()
    
    //MARK:
    // MARK: - 加载界面
    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "走后门", imgName: " ", font: 15, target: self, action: #selector(modalView))
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", imgName: " ", font: 15, target: self, action: #selector(dismissView))
        
        loadOAuthPage()
        self.view.backgroundColor = UIColor.white
    }
    
    func modalView(){
        print("点击了走后面  ,进行JS交互")
//                  let jsString = "document.getElementById('userId').value = '18606624988', document.getElementById('passwd').value = 'qazqaz'"
//        交互打开,快速填充
        let jsString = "document.getElementById('userId').value = '409377708@qq.com',document.getElementById('passwd').value = 'sunjianqin2'"
//
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    func dismissView(){
        print("点击了关闭")
        self.dismiss(animated: true)
    }
    
    func loadOAuthPage(){
        
        let String = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = URL(string: String)
        let  req = URLRequest(url: url!)
        webView.loadRequest(req)
        
    }
    
}

//MARK:
// MARK: - 封装起来

extension WBOAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
       SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //解决转圈延迟退出的效果
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //截取地址
        let url = request.url?.absoluteString ?? ""
        
        let flag = "code="
        if url.contains(flag) {
            let quere  = request.url?.query ?? ""
            let code = (quere as NSString).substring(from: flag.characters.count)
            
            //MARK:
            // MARK: - ---------------未用
            print(code)
            
            WBUserAccessViewModel.shared.getAccessToken(code: code, finished: { (isSuccess) in
                if !isSuccess{
                    SVProgressHUD.showError(withStatus: "请求失败")
                }
                //请求成功
                print("请求成功")
                
//                UIApplication.shared.keyWindow?.rootViewController = WBWelcomeViewController()
                NotificationCenter.default.post(name: NSNotification.Name(KChangeRootViewController), object: "WBwelcome")
                
            })
            
            return false
        }
        return true
        
    }
    
    /*
    //MARK:
    // MARK: - 获取token
    func getAccessToken(code:String){
        let url = "https://api.weibo.com/oauth2/access_token"
        
        let parameter = ["client_id": client_id ,
                         "client_secret": client_secret,
                         "grant_type": "authorization_code",
                         "code": code,
                         "redirect_uri":redirect_uri]
        HMNetworkTools.shared.request(method: .POST, urlString: url, parameters: parameter) { (response, error) in
            if error != nil{
                                SVProgressHUD.showError(withStatus: "网络请求失败")
                                return
                            }
                            //请求成功
                            print(response!)
                
                            self.getUserInfo(dict: response as! [String : Any])
                            
                        }

        }

        
        
    //MARK:
    // MARK: - 通过获取的token 来获取用户信息
    
    func getUserInfo(dict:[String:Any]){
    let urlString = "https:api.weibo.com/2/users/show.json"
    let token = dict["access_token"]!
    let uid = dict["uid"]!
  
    let parameters = ["access_token" : token,
                      "uid" : uid]
    print(parameters)
    
    HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
    if error != nil {
    SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
    return
    }
        
//        print(responseObject)
        
        //将得到的token 和 uesrInfo  两个字典合并,然后再存储
        var userInfo = responseObject as! [String:Any]
        
        for(key,value) in dict  {
            userInfo[key] = value
        }
        
        print(userInfo)
        
        //为模型赋值
        let userInfoAccount = WBUserAccount(dict:userInfo)
        //存档
        self.saveUserInfo(userInfoAccount: userInfoAccount)
        
        }
    }
 //存入
    func saveUserInfo(userInfoAccount:WBUserAccount){
        
        NSKeyedArchiver.archiveRootObject(userInfoAccount, toFile: path)
        print(path)
    }
    
    //取出
    func getUserInfoAccount()->WBUserAccount?{
      let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
        if let userAccount = account as?WBUserAccount {
            return userAccount
        }
        
        return nil
    }
    
    */
    
    
    
    
    
    
    
}







